<template>
  <div class="swiper-container">
    <div class="swiper-wrapper">
      <div
        class="swiper-slide"
        v-for="(item, index) in skuImageList"
        :key="item.id"
      >
        <img
          :src="item.imgUrl"
          @click="activeImg(index)"
          :class="{ active: index === defaultIndex }"
        />
      </div>
    </div>
    <div class="swiper-button-next"></div>
    <div class="swiper-button-prev"></div>
  </div>
</template>

<script>
import Swiper from "swiper";
export default {
  name: "ImageList",
  props: ["skuImageList"],
  methods: {
    //点击小图片大图片传参
    activeImg(index) {
      this.defaultIndex = index;
      //
      this.$bus.$emit("getZommIndex", index);
    },
  },
  data() {
    return {
      defaultIndex: 0,
    };
  },
  watch: {
    /* 监听swiperData的改变，然后准备实例化Swiper */
    skuImageList: {
      //立即执行 swiperData的数据不改变 下面的函数 不执行 所有样式 不出来 怎么办 立即执行呗
      immediate: true,
      handler() {
        if (!this.skuImageList.length) return;
        //因为实例化Swiper是操作的最新的dom，所有要写在$nextTick的回调函数中
        //$nextTick 将回调延迟到下次Dom更新 更新循环之后执行
        this.$nextTick(() => {
          // 配置swiper
          // ref的使用 捕捉 ref= XXX  获取 this.$refs.XXX
          new Swiper(".swiper-container", {
            // direction: "vertical", // 垂直切换选项
            direction: "horizontal", // 横向切换选项
            //一行显示几个图片
            slidesPerView: 4,
            // 在carousel mode下定义slides的数量多少为一组。 每次滚动切换多少张图片
            slidesPerGroup: 2,
            //出现bug 解决关闭循环模式 因为index混乱了
            // loop: true, // 循环模式选项

            // 如果需要分页器
            pagination: {
              el: ".swiper-pagination",
            },

            // 如果需要前进后退按钮
            navigation: {
              nextEl: ".swiper-button-next",
              prevEl: ".swiper-button-prev",
            },
          });
        });
      },
    },
  },
};
</script>

<style lang="less" scoped>
.swiper-container {
  height: 56px;
  width: 412px;
  box-sizing: border-box;
  padding: 0 12px;

  .swiper-slide {
    width: 56px;
    height: 56px;

    img {
      width: 100%;
      height: 100%;
      border: 1px solid #ccc;
      padding: 2px;
      width: 50px;
      height: 50px;
      display: block;

      &.active {
        border: 2px solid #f60;
        padding: 1px;
      }

      &:hover {
        border: 2px solid #f60;
        padding: 1px;
      }
    }
  }

  .swiper-button-next {
    left: auto;
    right: 0;
  }

  .swiper-button-prev {
    left: 0;
    right: auto;
  }

  .swiper-button-next,
  .swiper-button-prev {
    box-sizing: border-box;
    width: 12px;
    height: 56px;
    background: rgb(235, 235, 235);
    border: 1px solid rgb(204, 204, 204);
    top: 0;
    margin-top: 0;
    &::after {
      font-size: 12px;
    }
  }
}
</style>